#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include "cgic.h"
#include "session.h"

int set_session(char *username,char* password){
	if(strcmp(username,"yaomianfa")!=0 || strcmp(password,"st123456")!=0)return -1;
	
	
	char sfp[256];
	char str_now[11];
	char *session_id;
	time_t now;
	time(&now);
	sprintf(str_now,"%10d",now);
	//get a random session_id
	int r;
	srand(now);
	r = rand();
	session_id = (char*)malloc(17*sizeof(char));
	for(int i=0;i<16;i++){
		srand(r);
		r=rand();
		session_id[i]=r%26+'A';
	}
	session_id[16]='\0';
	
	
	//create session file
	strcpy(sfp,"./sess_");
	//strcat(sfp,"/sess_");
	strcat(sfp,session_id);
	
	FILE *sf = fopen(sfp,"w+");
	chmod(sfp,06777);
	
	if( sf == NULL){
		return -1;
	}
	
	//write session file
	fputs(str_now,sf);
	fputs("\n",sf); 
	fputs(username,sf);
	fputs("\n",sf);
	fputs(password,sf);
	fputs("\n",sf);
	fclose(sf);
	
	cgiHeaderCookieSetString("session_id", session_id, 
	86400,"/","192.168.232.200");
	return 0;
}

int has_session(){
	char session_id[17];
	char str[256];
	
	int ret = cgiCookieString("session_id", session_id,17);
	if(ret!=cgiFormSuccess){
		return 0;
	}
	
	strcpy(str,"./sess_");
	strcat(str,session_id);
	
	
	if (access(str, F_OK) == 0)//session存在
    {
		//判断该文件是否为过期文件
		char username[100];
		char passwd[100];
		char str_time[11];
		time_t now;
		FILE *sf = fopen(str,"r");
		if( sf == NULL){
			return 0;
		}
		
		char *find;
		fgets(str_time,12,sf);
		fgets(username,100,sf);
		find = strchr(username, '\n');          //查找换行符
		if(find)                            //如果find不为空指针
			*find = '\0';                    //就把一个空字符放在这里
		fgets(passwd,100,sf);
		find = strchr(passwd, '\n');          //查找换行符
		if(find)                            //如果find不为空指针
			*find = '\0';                    //就把一个空字符放在这里
		
		if(strcmp(username,"yaomianfa")!=0 || strcmp(passwd,"st123456")!=0){
			//显然用户更改了密码
			kill_session();
			return 0;
			
		}
		
		time(&now);
		if(now-atoi(str_time)>86400){
			//显然SESSION是过期的 用户拿了过期的SESSION
			kill_session();
			return 0;
		}
		
		fclose(sf);
		
        return 1;
    }
    else
    {
        return 0;
    }
	
	
}

void kill_session(){
	char session_id[17];
	char str[256];
	int ret = cgiCookieString("session_id", session_id,17);
	if(ret!=cgiFormSuccess){
		return 0;
	}
	strcpy(str,"./sess_");
	strcat(str,session_id);
	if (access(str, F_OK) == 0)//session存在 执行删除操作
    {
		remove(str);
	}
	
}

 /* int main(){
	if(set_session("yaomianfa","st123456")==0){
		printf("create sucess\n");
	}else{
		printf("create error\n");
	}
} */
 

